package com.dynamic.model.shiro.service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.dynamic.model.model.po.SysmanResource;
import com.dynamic.model.model.po.SysmanRole;
import com.dynamic.model.model.po.SysmanUser;
import com.dynamic.model.service.SystemUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;


public class ShiroDbRealm extends AuthorizingRealm {
	
	@Autowired
	private SystemUserService sysmanUserService;
	
	
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SysmanUser user = (SysmanUser) principals.fromRealm(getName()).iterator().next();
		user = this.sysmanUserService.get(user.getPid());
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		List<SysmanRole> roles = user.getRoles();
	
		Set<String>  permissions = new HashSet<String>();
		
		for(SysmanRole role : roles ){
			info.addRole(role.getName());
			for(SysmanResource resource : role.getResource()){
				/*if(SysmanResource.TYPE_MENU == resource.getResourceType() ){
					setMenuPerms(permissions, resource.getParent());
					permissions.add(resource.getName());
				}*/
				//setMenuPerms(permissions, resource.getParent());
				permissions.add(resource.getName());
                permissions.add(resource.getHref());
			}
		}
		
		info.addStringPermissions(permissions);
		
		return info;
	}
	
	private void setMenuPerms(Set<String> permissions, SysmanResource resource) {
		if(resource != null) {
			permissions.add(resource.getHref());
            permissions.add(resource.getName());
			if(resource.getParent()!=null){
				setMenuPerms(permissions, resource.getParent());
			}
		}
	}

	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken usernamePasswordToke = (UsernamePasswordToken)token;
		
		String username = usernamePasswordToke.getUsername();
		
		SysmanUser user  = sysmanUserService.findByName(username);
		
		sysmanUserService.evict(user);
		//user.setRoles(null);
		
		if(user==null){
			throw new  UnknownAccountException("用户帐号不存在！");
		}
		
		if(user.getStatus()!=SysmanUser.STATUS_NORMAL){
			throw new  LockedAccountException("用户帐号已停用，请联系系统管理员！");
		}
		if(user.getRoles().size()==0){
			throw new ExcessiveAttemptsException("没有关联角色");
		}
		return new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getPassword()),getName());
	}

}
